import fetch from 'isomorphic-fetch';
import { NavBar } from 'antd-mobile';

// 增加超时
function _fetch(fetch, timeout) {
  return Promise.race([
    fetch,
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error('request timeout')), timeout);
    })
  ]);
}
// 自定义fetch7
const fetchNew = (url = '', type = 'get', parames = {}, timeout = 50000) => {
  let option = {};
  let urlNew = '';
  if(type == 'get'){
    option = {
      method: 'get',
      credentials: 'same-origin',
      headers : {
       'Content-Type': 'application/json;charset=utf-8'
      }
    }
    let optionsNew = '';
    for(let i in parames){
      if(optionsNew == ''){
        optionsNew += ('?'+ i +'=' + parames[i])
      }else{
        optionsNew += ('&'+ i +'=' + parames[i])
      }
    }
    urlNew = url + optionsNew;
  }else if(type == 'post'){
    option = {
      method: 'post',
      credentials: 'same-origin',
      headers : {
       'Content-Type': 'application/json;charset=utf-8'
     },
     body: JSON.stringify(parames)
    }
    urlNew = url;
  }
  return _fetch(
  fetch(urlNew, option), timeout)
  .then(function(response) {
    console.log('response',response);
    return response.json();
  }).catch(function(res) {
    console.log('接口请求失败！');
  })
}

export default fetchNew
